<?php

namespace Shahu\Common\service;

use Shahu\Common\common\RedisCache;
use Shahu\Common\constant\AuthRedisKeyConstant;
use Shahu\Common\model\ApplicationModel;

class ApplicationService
{
    /**
     * 获取租户缓存
     * @param $tenant
     * @return array
     */
    public static function getTenantCache($tenant) : array
    {
        $tenant_redis_key = AuthRedisKeyConstant::APPLICATION_TENANT_MAP;
        if (!RedisCache::exists($tenant_redis_key)) {
            //获取全部租户
            $map = self::setApplicationCache();
            $tenant_cache = $map[$tenant] ?? '';
        } else {
            //获取单个
            $tenant_cache = RedisCache::hGet($tenant_redis_key, $tenant);
            if (empty($tenant_cache)) {
                //获取全部租户
                $map = self::setApplicationCache();
                $tenant_cache = $map[$tenant] ?? '';
            }
        }
        return json_decode($tenant_cache, true);
    }


    /**
     * 设置app缓存
     * @return array
     */
    public static function setApplicationCache(): array
    {
        $app_arr = ApplicationModel::selectAll();
        if (!empty($app_arr)) {
            $app_map = [];
            foreach ($app_arr as $tmp_app) {
                $app_map[$tmp_app['tenant']] = json_encode($tmp_app);
            }
            RedisCache::hMset(AuthRedisKeyConstant::APPLICATION_TENANT_MAP, $app_map, RedisCache::$twenty_day);
            return $app_map;
        }
        return [];
    }


}